package com.helpustotravel.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.helpustotravel.core.ServletBase;
import com.helpustotravel.model.dao.PhotoDAO;
import com.helpustotravel.model.dao.PositionDAO;
import com.helpustotravel.model.dao.TravellerDAO;
import com.helpustotravel.model.jdo.Position;
import com.helpustotravel.model.jdo.Traveller;
import com.helpustotravel.utils.DateUtils;

@SuppressWarnings("serial")
public class GetTravellerInfosServlet extends ServletBase {
	
	public static String NAME = "GetTravellerInfos";
	
	protected HttpServletResponse doTache(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		// mise en majuscule
		String name = req.getParameter("name").toUpperCase();
		// on ne garde que le premier mot
		String[] names = name.split(" ");
		if(names.length > 1) {
			name = names[0];
		}
		
		TravellerDAO travellerDao = new TravellerDAO(pm);
		Traveller traveller = travellerDao.getTraveller(name);
		
		String json = "";
		
		if(traveller != null) {
			PhotoDAO photoDao = new PhotoDAO(pm);
			String profilPhotoURL = photoDao.getProfilPhotoURL(traveller.getName());
			
			/* 
			 * {"name": name, "type": type, "story": story, "positions": 
				[
					{"date": date, "adresse": adresse, "x": x, "y": y}
					{"date": date, "adresse": adresse, "x": x, "y": y}
					{"date": date, "adresse": adresse, "x": x, "y": y}
				]} */

			json = "{\"name\":\"" + traveller.getName() +
					"\",\"completeName\":\"" + traveller.getCompleteName() + 
					"\",\"type\":\"" + traveller.getType() + 
					"\",\"profilPhotoURL\":\"" + profilPhotoURL + 
					//"\",\"story\":\"" + StringEscapeUtils.escapeJavaScript(traveller.getStory()) + 
					"\",\"positions\":[";
			
			List<Long> positions = traveller.getPositionIds();
			PositionDAO positionDao = new PositionDAO(pm);
			
			for(int i = 0; i < positions.size(); i++) {
				long id = positions.get(i);
				Position position = positionDao.getPosition(name, id);
				
				if(position != null) {
					json += "{\"date\":\"" + DateUtils.formatDate(position.getDate()) + 
							"\",\"adresse\":\"" + position.getAdresse() +
							"\",\"x\":" + String.valueOf(position.getX()) + 
							",\"y\":" + String.valueOf(position.getY()) + "}";
					
					if(i < (positions.size() - 1)) {
						json += ",";
					}
				}

			}

			json += "]}";

		} else {
			
			json = "{\"name\":\"null\"}";
			
		}
		
		resp.getWriter().print(json);
		return resp;
	}
}
